<template>
	<div class="coupon-get">
		<!--<div class="c-red">卓恩优惠券领取</div>-->
		<!--信息-->

		<div>
			<!--<el-button type="danger" @click="clearCache()">清理localStorage</el-button>-->
		</div>

		<!--
		<div>卡券couponId:{{couponId}}</div>
		<div>推荐人userId:{{referrer}}</div>
		<div>客户 openid:{{openId}}</div>
		<div>客户：isLoginExternalUser:{{ isLoginExternalUser }}（{{externalUserId}}）</div>
		<div>登录信息{{ userInfo }}</div>
		<div>
			<div class="c-red">开发阶段中，按钮不要乱点击哦</div>

			<el-button type="danger" @click="login"  v-if="!isLoginUser">企业微信手动登录</el-button>
			<el-button type="danger" @click="loginWx"  v-if="!isLoginExternalUser">微信公众号手动登录</el-button>

			<el-button type="success" @click="bindOpenIdToExternalUser" >绑定openid</el-button>
		</div>-->

		<!--优惠券  v-if="isLoginUser || isWxlogin"  -->
		<div class="coupon-detail" v-if="isLoginUser==true || isLoginExternalUser==true" @click="actFetchCoupon()">
			<div class="stockName">{{couponDetail.stockName}}</div>
			<div class="stockId">卡券号：{{couponDetail.stockId}}</div>
			<div class="condition">使用条件：满{{couponDetail.transactionMinimum}}减{{couponDetail.discountAmount}}</div>
			<div>开始时间：{{couponDetail.availableBeginTime}}</div>
			<div>结束时间：{{couponDetail.availableEndTime}}</div>
			<!--狗日的element-ui plus他妈按钮的样式发神经-->
			<div class="btn-group" v-if="isWxlogin">
				<!--<el-button type="success" @click="actFetchCoupon()">去微信官方页面领取>></el-button>-->
				<span >去微信官方页面领取>></span>
			</div>
		</div>
		<!--<div v-else>登录中,请稍后...</div>-->
	</div>
</template>

<script>
import mixins from "@/mixins/mixins";
import mixinsWx from "@/mixins/mixinsWx";
import {
	apiBindOpenIdToExternalUser,
	apiCouponDetailOfBusiness,
	apiFetchBusinessCouponUrl,
	apiShowCouponEvent,
} from "@/axios/api";
import { isEmpty } from "@/utils/common";

export default {
	name: "couponGet",
	mixins:[mixins,mixinsWx],
	data(){
		return {
			couponId : "",//优惠券码，从url得到的
			referrer : "",// 推荐人，从url得到的，store中有了，所以加了个2
			openId : "",//openid
			////////////////////////////////复杂数据/////////////////////////
			//优惠券数据
			couponDetail:{
				stockName:"",
			},
		}
	},
	computed:{
		//是否已经登录微信（openId）
		isWxlogin(){
			return this.openId  ?  true : false
		}
	},
	created() {
		//注意这里应该要保存在最前面执行，因为跳转回来时，是不带url参数的，应该从localstorage里面获取
		this.paramsProcessing()//处理url中的参数，与本地储存进行联合处理

		//环境判断
		if(this.dev==true){//开发环境时，直接读取优惠券信息，不调用初始化的东西
			this.getCouponDetail()
		}else{//生产环境
			this.init()
		}
	},

	methods:{
		//初始化
		init() {
			if(this.isLoginUser){ //从员工工作台跳转过来，肯定已经登录，直接加载券数据,
				this.notify('当前身份是员工，直接读取优惠券数据','success')
				this.getCouponDetail()
			}else{
				// 没有openid（会写入localstorage并读取），就先进行公众号登录,跳转回来后，再进行企业微信登录
				if(!this.openId){
					this.loginWx() //公众号登录
				}else{
					this.login() //进行企业微信登录
				}
			}
		},

		//微信公众号登录（得到openId）
		loginWx() {
			console.log('进行公众号登录')
			/*Swal.fire({
				// position:'top',
				html: '准备进行公众号登录跳转，请稍候...',
				// type: "success",
				// showConfirmButton: true,
				timer:10000,
				backdrop:true,//遮罩
				allowOutsideClick: false,//允许外部点击关闭
				onBeforeOpen: () => { Swal.showLoading() },
				onAfterClose: () => {console.log("关闭")}
			});*/
			let appid = "wx35839eba72c12a73" // 公众号的id？？
			let _urlBack = "http://www.qzzhuoen.com/#/loginWx"
			let redirect_uri = encodeURIComponent(_urlBack);   //使用 urlEncode 对链接进行处理
			let codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize";
			codeUrl = codeUrl + "?appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=jetcms#wechat_redirect";

			setTimeout(() => {
				window.location.href = codeUrl
			},200)
		},

		//企业微信登录逻辑
		login (){
			console.log('进行企业微信登录')
			if(this.isLoginExternalUser==false){
				let url = this.getRedirectUrlWorkder() //使用带参数的方法来组织跳转url
				console.log('准备进行登录跳转'+url)
				/*Swal.fire({
					position:'top',
					html: '准备进行企业微信登录跳转，请稍候...',
					// type: "success",
					// showConfirmButton: true,
					timer:10000,
					backdrop:true,//遮罩
					allowOutsideClick: false,//允许外部点击关闭
					onBeforeOpen: () => { Swal.showLoading() },
					onAfterClose: () => {console.log("关闭")}
				});*/
				setTimeout(() => {
					window.location.href = url
				}, 200) //定时跳转

			}else if(this.isLoginExternalUser==true){//外部客户在企业微信登录跳转回来时，会走这里
				// this.notify('你是客户，已经登录，读取优惠券数据','success')
				this.getCouponDetail()//读取优惠券详情
				this.bindOpenIdToExternalUser() //绑定openid
				this.showCouponEvent() //记录发券事件,佣金发放
			}
		},

		//发送打开优惠券事件
		showCouponEvent() {
			apiShowCouponEvent({
				externalUserid: this.externalUserId,
				openId        : this.openId,
				couponId      : this.couponId,
				referrer      : this.referrer,
			}).then((res)=>{
				// this.notify(res.resultMsg,'info',10000)
			})

		},

		//绑定openid
		bindOpenIdToExternalUser() {
			apiBindOpenIdToExternalUser(
				{
					externalUserid: this.externalUserId,
					openId        : this.openId,
				}
			).then((res)=>{
				setTimeout(() => {
					// this.notify(res.resultMsg,'info',10000)
				},1000)
			})
		},

		//处理参数，url有参数就存到localstorage，没有就从localstorage中读取
		paramsProcessing(){

			// 从loginWx登录页面读取写入的openid
			this.openId = localStorage.getItem("openId")

			//处理优惠券id
			let { couponId,userId }= this.$route.query
			console.log('couponId,userId',couponId,userId)
			if(isEmpty(couponId)){
				console.log('参数中没有couponId,将从localstorage中读取')
				couponId = localStorage.getItem("couponId")
			}else{
				console.log('参数中有couponId,将保存到localstorage中')
				localStorage.setItem("couponId",couponId)
			}

			//处理员工id，对客户来说也就是推荐人
			if(isEmpty(userId)){
				console.log('参数中没有userId,将从localstorage中读取')
				userId = localStorage.getItem("userId")
			}else{
				console.log('参数中有userId,将保存到localstorage中')
				localStorage.setItem("userId",userId)
			}

			//写入到data中
			this.couponId = couponId
			this.referrer = userId

		},

		//读取优惠券信息
		getCouponDetail() {
			apiCouponDetailOfBusiness({
				stockId:this.couponId
			}).then((res)=>{
			    if(res.resultFlag==true){
					this.couponDetail = res.data
			    }else{
					this.$message.error(res.resultMsg)
			    }
			})
		},

		//领取优惠券
		actFetchCoupon() {
			if(this.isWxlogin==true){ //当前是外部客户才跳转
				apiFetchBusinessCouponUrl({
					couponId : this.couponId,
					openId : this.openId
				}).then((res)=>{
					if(res.resultFlag==true){
						// this.notify("即将跳转优惠券领取页面..."+res.data,"success")
						setTimeout(() => {
							window.location.href = res.data
						},50)
					}else{
						this.notify("获取优惠券领取url失败","error")
					}
				})
			}
		},

	}
}
</script>

<style lang="less" scoped>
.coupon-detail{
	font-size:10px;
	max-width: 400px;
	color:#fff;
	background-color: #417ff0;;
	border-radius:5px;
	padding:1.5em;
	box-shadow: 3px 3px 3px rgba(100,100,100,0.2);
	& > * {font-size:1.4em;}
	.stockName{
		color:rgba(255,255,255,0.8);font-size: 2.4em;font-weight: bold;
		margin:0em 0em .5em;
		padding:0em 0em .5em;
		border-bottom:1px solid rgba(255,255,255,0.3)
	}
	.stockId{}
	.condition{}
	.btn-group {
		.flex-jcfe();
		margin-top: 0.5em;
	}
}
</style>